//
//  NSObject+Function.m
//  KKCategory
//
//  Created by liaozhenming on 16/5/17.
//  Copyright © 2016年 liaozhenming. All rights reserved.
//

#import "NSObject+Function.h"
#import <objc/runtime.h>

#define Prefix @"kk_"

@implementation NSObject (Function)

- (void)kk_parserJsonDictionary:(NSDictionary*)jsonDictionary {
    
    if (![jsonDictionary isKindOfClass: [NSDictionary class]]) {
        return;
    }
    
    NSObject *targetObject = self;
    
    while (targetObject.class != [NSObject class]) {
        
        unsigned int count = 0;
        //成员变量
        Ivar *ivars = class_copyIvarList(targetObject.class, &count);
        
        for (int i = 0; i < count; i++) {
            
            Ivar ivar = ivars[i];
            
            //  变量名称
            NSString *ivarName = [[NSString alloc] initWithUTF8String: ivar_getName(ivar)];
            
            //  变量类型
            NSString *ivarType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
            NSLog(@"ivar = %@|%@", ivarType, ivarName);
            
            NSString* key = ivarName;
            ivarName = [ivarName substringFromIndex: 1];
            
            key = [key substringFromIndex: 1];
            
            if ([key hasPrefix: Prefix] && Prefix.length) {
                key = [key substringFromIndex: Prefix.length];
            }
            
            //  获取值
            id value = jsonDictionary[key];
            if (value != nil && ![value isKindOfClass: [NSNull class]]) {
                [self setValue: value forKey: ivarName];
            }
        }
        free(ivars);
        
        targetObject = [targetObject.superclass new];
    }
}

- (NSString*)kk_stringValue {
    
    if ([self isKindOfClass: [NSNumber class]]) {
        return [NSString stringWithFormat: @"%@",self];
    }
    else if ([self isKindOfClass: [NSArray class]] || [self isKindOfClass: [NSDictionary class]]) {
        NSData *data = [NSJSONSerialization dataWithJSONObject: self options: NSJSONWritingPrettyPrinted error: nil];
        return [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    }
    else if ([self isKindOfClass: [NSString class]]) {
        return (NSString*)self;
    }
    else if ([self isKindOfClass: [NSObject class]]) {
        return self.description;
    }
    else {
        return @"";
    }
}

@end
